//
//  HNCourseListVM.m
//  优学荟管理系统
//
//  Created by 星道 on 2017/10/7.
//  Copyright © 2017年 星道三好. All rights reserved.
//

#import "HNCourseListVM.h"
#import "ZYAddStrongCouseController.h"
#import "HNHandleCourseVC.h"

@implementation HNCourseListVM
{
    UITableView *_TableView;
    NSInteger _Index;
    NSInteger _TempIndex;
    NSMutableArray *_DataArr;
    NSString *_searchName;
}

/** 配置tableView */
- (void)ConfigTableView:(UITableView *)TableView {

    _searchName = @"";
    _TableView = TableView;
    _DataArr = [NSMutableArray array];
    _TableView.tableFooterView = [UIView new];
    _TableView.tableHeaderView = [UIView new];
    [_TableView registerNib:[UINib nibWithNibName:[HNCourseListCell description] bundle:nil] forCellReuseIdentifier:@"Cell"];
    _TableView.rowHeight = UITableViewAutomaticDimension;
    _TableView.estimatedRowHeight = 250;
    _TableView.delegate = self;
    _TableView.dataSource = self;
    _TableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        _TempIndex = _Index;
        _Index = 1;
        [self RefreshData];
    }];
    _TableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

        [self RefreshData];
    }];
    [_TableView.mj_header beginRefreshing];
}

/** 请求失败处理下标 */
- (void)MgrPage {
    if (_Index == 1) {
        _Index = _TempIndex;
    }
}

/** 发出请求 */
- (void)RefreshData {

    NSDictionary *Params = @{
                             @"action"      :@"getLessonList",
                             @"pageNumber"  :@(_Index),
                             @"oid"         :[AccountTool shareAccountTool].currentAccount.oid,
                             @"searchName"  :_searchName
                             };
    [NetManager Get:LLBaseURL(@"yxhUser.do") Auth:YES Params:Params Success:^(id Obj) {
        [_TableView.mj_footer endRefreshing];
        [_TableView.mj_header endRefreshing];
        if ([Obj[@"code"] isEqualToNumber:@1000]) {
            if ([Obj[@"t"][@"dataList"] count] <= 0) {
                [_TableView.mj_footer endRefreshingWithNoMoreData];
            } else {
                if (_Index == 1) {
                    [_DataArr removeAllObjects];
                }
                [Obj[@"t"][@"dataList"] enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    [_DataArr addObject:[CourseListModel HNObjectValuesForKey:obj]];
                }];
                _Index += 1;
                [_TableView reloadData];
            }
        } else {
            [self MgrPage];
            [HUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [self MgrPage];
        [HUD showError:NetErr];
        [_TableView.mj_footer endRefreshing];
        [_TableView.mj_header endRefreshing];
    }];
}


#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _DataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    CourseListModel *Model = _DataArr[indexPath.row];
    HNCourseListCell *Cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    Cell.Model = Model;
    Cell.Delegate = (id)self.VC;
    /** 开设加强课 */
    
    __weak typeof(self) weakSelf = self;
   Cell.ClickCreatCourse = ^(NSString *lessonId) {


        [weakSelf ClickCreatCourse:[Model.ID stringValue] yaosuModel:Model.ElementCountArr];
    };
    return Cell;
}

/** 开设加强课 */
    
    
    
- (void)ClickCreatCourse:(NSString *)lessonId yaosuModel:(NSMutableArray *)arr {

  



    // 先获取老师的信息
    [self RefreshDataWithTeacher:^(NSArray<TeacherCourseSelectModel *> *Arr) {

        NSMutableArray *TitleArr = [NSMutableArray array];
        [Arr enumerateObjectsUsingBlock:^(TeacherCourseSelectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [TitleArr addObject:obj.petName];
        }];
        // 弹窗并选择老师
        TeacherCourseSelectView *View = [TeacherCourseSelectView ConfigWithArr:[TitleArr copy] Complete:^(NSInteger Index) {

            ZYAddStrongCouseController *VC = [[ZYAddStrongCouseController alloc] init];
            // 声明我这是增加课程

            VC.tearchIds = [[Arr[Index] uid] stringValue];

            VC.dataSelectSource = arr;
            VC.lessionId = lessonId;
            VC.titleName = @"开设加强课";
            
            VC.popBlock = ^{
              
                [_DataArr removeAllObjects];
                _TempIndex = _Index = 1;
                [_TableView reloadData];
                [_TableView.mj_header beginRefreshing];
            };
            

            [[self getCurrentVC].navigationController pushViewController:VC animated:YES];
        }];
        View.Title.text = @"请选择课程老师";
    }];
















}

/** 刷新 */
- (void)RefreshTableView {

    _Index = _TempIndex = 1;
    [_DataArr removeAllObjects];
    [_TableView reloadData];
    [_TableView.mj_header beginRefreshing];
}






/** 进入添加课程的VC */
- (void)GoAddCourse
{
    
    HNHandleCourseVC *VC = [[HNHandleCourseVC alloc] init];
    // 声明我这是修改课程
    VC.type = HNHandleCourseTypeAdd;
    VC.PopOfRefresh = ^ {
        
        
            [_TableView.mj_header beginRefreshing];
    };
    [self.VC.navigationController pushViewController:VC animated:YES];
    return;
    
    // 先获取老师的信息
    [self RefreshDataWithTeacher:^(NSArray<TeacherCourseSelectModel *> *Arr) {

        NSMutableArray *TitleArr = [NSMutableArray array];
        [Arr enumerateObjectsUsingBlock:^(TeacherCourseSelectModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [TitleArr addObject:obj.petName];
        }];
        // 弹窗并选择老师
        TeacherCourseSelectView *View = [TeacherCourseSelectView ConfigWithArr:[TitleArr copy] Complete:^(NSInteger Index) {

            AddCourseVC *VC = [[AddCourseVC alloc] init];
            // 声明我这是增加课程
            VC.mode = AddCourseAdd;
            VC.TeacherID = [Arr[Index] uid];
            VC.RefreshUI = ^{
                [_TableView.mj_header beginRefreshing];
            };
            [self.VC.navigationController pushViewController:VC animated:YES];
        }];
        View.Title.text = @"请选择课程老师";
    }];
}


- (void)RefreshDataWithTeacher:(void (^)(NSArray <TeacherCourseSelectModel *>*Arr))Complete {

    [MBProgressHUD showHUD];
    NSDictionary *Params = @{
                             @"action":@"getTeacherByOid",
                             @"oid":[AccountTool shareAccountTool].currentAccount.oid
                             };
    [NetManager Get:LLBaseURL(@"lesson.do") Auth:YES Params:Params Success:^(id Obj) {

        if ([Obj[@"code"] isEqualToNumber:@1000]) {

            NSMutableArray *MutableArr = [NSMutableArray array];
            [Obj[@"t"] enumerateObjectsUsingBlock:^(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {

                [MutableArr addObject:[TeacherCourseSelectModel HNObjectValuesForKey:obj]];
            }];
            dispatch_async(dispatch_get_main_queue(), ^{

                Complete ? Complete ([MutableArr copy]) : nil ;
            });


        } else {
            [MBProgressHUD showError:Obj[@"msg"]];
        }
    } Fail:^(NSError *Error) {
        [MBProgressHUD showError:NetErr];
    }];
}



- (UIViewController *)getCurrentVC {
    
    UIWindow *window = [[UIApplication sharedApplication].windows firstObject];
    if (!window) {
        return nil;
    }
    UIView *tempView;
    for (UIView *subview in window.subviews) {
        if ([[subview.classForCoder description] isEqualToString:@"UILayoutContainerView"]) {
            tempView = subview;
            break;
        }
    }
    if (!tempView) {
        tempView = [window.subviews lastObject];
    }
    
    id nextResponder = [tempView nextResponder];
    while (![nextResponder isKindOfClass:[UIViewController class]] || [nextResponder isKindOfClass:[UINavigationController class]] || [nextResponder isKindOfClass:[UITabBarController class]]) {
        tempView =  [tempView.subviews firstObject];
        
        if (!tempView) {
            return nil;
        }
        nextResponder = [tempView nextResponder];
    }
    return  (UIViewController *)nextResponder;
}


- (void)Search:(NSString *)str {
    
    _searchName = str;
    [_DataArr removeAllObjects];
    [_TableView reloadData];
    _Index = _TempIndex = 1;
    [_TableView.mj_header beginRefreshing];
}

@end
